package org.stvd.controller.workflow;

import java.io.ByteArrayInputStream;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.activiti.bpmn.converter.BpmnXMLConverter;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.editor.constants.ModelDataJsonConstants;
import org.activiti.editor.language.json.converter.BpmnJsonConverter;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.Model;
import org.activiti.engine.repository.ModelQuery;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.stvd.common.aspectj.lang.annotation.Log;
import org.stvd.common.aspectj.lang.enums.BusinessType;
import org.stvd.common.utils.InterfaceResult;
import org.stvd.common.workflow.enums.WorkflowTypeEnum;
import org.stvd.controller.BaseController;
import org.stvd.core.dto.QueryResult;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

/**
 * @Title ModelController
 * @Destribution 流程模型控制类
 * @author houzx
 * @date 2020年10月27日
 */
@Controller
@RequestMapping(value = "/workflow/model")
public class ModelController extends BaseController{

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    RepositoryService repositoryService;
    
    private String tmpURL = "/workflow/model/";

    /**
     * 模型列表
     */
    @RequestMapping(value = "manage")
    public String modelList() {
        QueryResult<Model> queryResult = new QueryResult<Model>();
        ModelQuery query = repositoryService.createModelQuery();
        queryResult.setTotal(query.count());
        queryResult.setRows(query.listPage((pageNo - 1)/pageSize, pageSize));
        if (query.count() % pageSize == 0) {
            queryResult.setPageCount( (int)(query.count() / pageSize) );
        } else {
            queryResult.setPageCount( (int)(query.count() / pageSize) + 1 );
        }
        queryResult.setPageIndex((int) Math.floor((pageNo - 1)/pageSize) + 1);
        if (queryResult.getPageCount() > 0 && queryResult.getPageCount() < queryResult.getPageIndex()) {
            queryResult.setPageIndex(queryResult.getPageIndex() - 1);
        }
        map.put("queryResult", queryResult);
        return tmpURL + "ModelManage.html";
    }

    /**
     * @Destribution 新增流程模型 
     * @return
     */
    @GetMapping(value = "add")
    public String onWorkflowModelAdd(){
        map.put("workflowTypeMap", WorkflowTypeEnum.workflowTypeMap);
        return tmpURL + "ModelAdd.html"; 
    }
    
    @Log(title = "新增工作流程模型", businessType = BusinessType.INSERT)
    @PostMapping(value = "add")
    @ResponseBody
    public InterfaceResult<Map<String, Object>> onWorkflowModelAddAction(
            @RequestParam("key") String key, @RequestParam("name") String name,
            @RequestParam("version") Integer version, @RequestParam("description") String description,
        HttpServletRequest request, HttpServletResponse response) {
        InterfaceResult<Map<String, Object>> result = new InterfaceResult<Map<String,Object>>();
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            ObjectNode editorNode = objectMapper.createObjectNode();
            editorNode.put("id", "canvas");
            editorNode.put("resourceId", "canvas");
            ObjectNode stencilSetNode = objectMapper.createObjectNode();
            stencilSetNode.put("namespace", "http://b3mn.org/stencilset/bpmn2.0#");
            editorNode.put("stencilset", stencilSetNode);
            Model modelData = repositoryService.newModel();

            ObjectNode modelObjectNode = objectMapper.createObjectNode();
            modelObjectNode.put(ModelDataJsonConstants.MODEL_NAME, name);
            modelObjectNode.put(ModelDataJsonConstants.MODEL_REVISION, 1);
            description = StringUtils.defaultString(description);
            modelObjectNode.put(ModelDataJsonConstants.MODEL_DESCRIPTION, description);
            modelData.setMetaInfo(modelObjectNode.toString());
            modelData.setKey(StringUtils.defaultString(key));
            modelData.setName(name);
            modelData.setVersion(version);

            repositoryService.saveModel(modelData);
            repositoryService.addModelEditorSource(modelData.getId(), editorNode.toString().getBytes("utf-8"));
            result.setMsg("模型创建成功！");
        } catch (Exception e) {
            result.setError("创建模型失败：" + e);
            logger.error("创建模型失败：", e);
        }
        return result;
    }

    /**
     * 根据Model部署流程
     */
    @Log(title = "部署工作流程", businessType = BusinessType.UPDATE)
    @PostMapping(value = "deploy/{modelId}")
    @ResponseBody
    public InterfaceResult<Map<String, Object>> onWorkflowModelDeployAction(
        @PathVariable("modelId") String modelId, RedirectAttributes redirectAttributes) {
        InterfaceResult<Map<String, Object>> result = new InterfaceResult<Map<String,Object>>();
        try {
            Model modelData = repositoryService.getModel(modelId);
            ObjectNode modelNode = (ObjectNode) new ObjectMapper().readTree(repositoryService.getModelEditorSource(modelData.getId()));
            byte[] bpmnBytes = null;

            BpmnModel model = new BpmnJsonConverter().convertToBpmnModel(modelNode);
            bpmnBytes = new BpmnXMLConverter().convertToXML(model);

            String processName = modelData.getName() + ".bpmn20.xml";
            Deployment deployment = repositoryService.createDeployment().name(modelData.getName()).addString(processName, new String(bpmnBytes)).deploy();
            redirectAttributes.addFlashAttribute("message", "部署成功，部署ID=" + deployment.getId());
            result.setMsg("部署成功，部署ID=" + deployment.getId());
        } catch (Exception e) {
            result.setError("模型部署流程失败："+ e.getMessage());
            logger.error("模型部署流程失败：modelId={}", modelId, e);
        }
        return result;
    }

    /**
     * 导出model对象为指定类型
     * @param modelId 模型ID
     * @param type    导出文件类型(bpmn\json)
     */
    @Log(title = "导出流程模型", businessType = BusinessType.EXPORT)
    @RequestMapping(value = "export/{modelId}/{type}")
    public void export(@PathVariable("modelId") String modelId,
       @PathVariable("type") String type, HttpServletResponse response) {
        try {
            Model modelData = repositoryService.getModel(modelId);
            BpmnJsonConverter jsonConverter = new BpmnJsonConverter();
            byte[] modelEditorSource = repositoryService.getModelEditorSource(modelData.getId());

            JsonNode editorNode = new ObjectMapper().readTree(modelEditorSource);
            BpmnModel bpmnModel = jsonConverter.convertToBpmnModel(editorNode);

            // 处理异常
            if (bpmnModel.getMainProcess() == null) {
                response.setStatus(HttpStatus.UNPROCESSABLE_ENTITY.value());
                response.getOutputStream().println("no main process, can't export for type: " + type);
                response.flushBuffer();
                return;
            }
            String filename = "";
            byte[] exportBytes = null;
            String mainProcessId = bpmnModel.getMainProcess().getId();
            if (type.equals("bpmn")) {
                BpmnXMLConverter xmlConverter = new BpmnXMLConverter();
                exportBytes = xmlConverter.convertToXML(bpmnModel);
                filename = mainProcessId + ".bpmn20.xml";
            } else if (type.equals("json")) {
                exportBytes = modelEditorSource;
                filename = mainProcessId + ".json";
            }

            ByteArrayInputStream in = new ByteArrayInputStream(exportBytes);
            IOUtils.copy(in, response.getOutputStream());

            response.setHeader("Content-Disposition", "attachment; filename=" + filename);
            response.flushBuffer();
        } catch (Exception e) {
            logger.error("导出model的xml文件失败：modelId={}, type={}", modelId, type, e);
        }
    }
    
    /**
     * @Destribution  删除流程模型
     * @param modelId
     * @return
     * @throws Exception
     */
    @Log(title = "删除流程模型", businessType =  BusinessType.DELETE)
    @PostMapping(value = "del")
    @ResponseBody
    public InterfaceResult<Map<String, Object>> onWorkflowModelDelete(String modelId) throws Exception {
        InterfaceResult<Map<String, Object>> result = new InterfaceResult<Map<String,Object>>();
        try {
            repositoryService.deleteModel(modelId);
            result.setMsg("模型‘" + modelId + "’删除成功！");
        } catch (Exception e) {
            e.printStackTrace();
            result.setError("删除模型" + modelId + "失败！<br/>失败原因：" + e.getMessage());
        }
        return result;
    }
}